package com.example.SOPVersionChain.controller;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CustomErrorController implements ErrorController {

    /**
     * 处理错误请求
     * @param request HTTP请求
     * @param model 模型
     * @return 错误页面
     */
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        String errorMsg = "未知错误";
        
        if (status != null) {
            Integer statusCode = Integer.valueOf(status.toString());
            
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                errorMsg = "找不到请求的页面";
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                errorMsg = "服务器内部错误";
            } else if (statusCode == HttpStatus.FORBIDDEN.value()) {
                errorMsg = "无权限访问此页面";
            }
            
            model.addAttribute("statusCode", statusCode);
        }
        
        model.addAttribute("errorMsg", errorMsg);
        return "error";
    }
} 